package com.etime.shycourse.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etime.shycourse.config.Tools;
import com.etime.shycourse.dao.OrgTeacherMapper;
import com.etime.shycourse.dao.OrganizationMapper;
import com.etime.shycourse.dao.SysUserMapper;
import com.etime.shycourse.dto.CurrentUser;
import com.etime.shycourse.dto.OrgTeacherDtoS;
import com.etime.shycourse.dto.UserTeacherDto;
import com.etime.shycourse.pojo.Organization;
import com.etime.shycourse.services.interfaces.OrgTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * -2 ：独立入驻教师 服务实现类
 * </p>
 *
 * @author wb
 * @since 2021-12-14
 */
@Service
public class OrgTeacherServiceImpl implements OrgTeacherService {
    @Autowired
    SysUserMapper sysuserMapper;
    @Autowired
    OrgTeacherMapper orgTeacherMapper;
    @Autowired
    OrganizationMapper orgMapper;

    @Autowired
    Tools tools;

    /**
     * 分页查询机构教师 信息
     * 1根据用户id 查询到所在机构id
     * 2再进行查询 sysUser、teacher信息
     * 可以 使用用户名进行查找
     * 教师列表数据
     *
     * @param dtoS     中的用户的name
     * @param pagenum  页码
     * @param pagesize 第几页
     * @return OrgTeacherDto
     */
    @Override
    public Page<OrgTeacherDtoS> selectOrgTeacherDtoByPage(OrgTeacherDtoS dtoS, Long pagenum, Long pagesize, String token) {
        CurrentUser user = tools.getCurrentUserFromRedis (token);
        /**
         * 当前端没有传分页数据时 就使用 page默认的值
         * pagesize = 1L
         * size = 10L;
         * */
        Page<OrgTeacherDtoS> page;
        if (pagenum != null & pagesize != null) {
            page = new Page<> (pagenum, pagesize);
        } else {
            page = new Page<> ();
        }

        if (dtoS.getUsertruename () != null) {
            dtoS.setUsertruename ('%' + dtoS.getUsertruename () + '%');
            // 设置机构id
            return orgTeacherMapper.selectOrgByPage (page, user.getOrgid (), dtoS.getUsertruename ());
        }
        // 根据机构id 获取机构教师列表分页
        // 机构不存在
        // 设置机构id
        return orgTeacherMapper.selectOrgByPage (page, user.getOrgid (), null);
    }

    /**
     * 增加 保存机构教师，
     * 1 然后再操作用户表 新增用户字段
     * 2 操作教师表  新增教师表字段
     * 保存
     * <p>
     * 字段有：用户名，密码，姓名，专业，联系电话，Email，照片；用户状态=1；是否教师=1；是否销售人员=0；
     *
     * @param orgTeacherDtoS 用户实体(教师)
     * @return 0失败；1成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertOrgTeacherDto(OrgTeacherDtoS orgTeacherDtoS, String token) {
        if (orgTeacherDtoS != null) {
            CurrentUser user = tools.getCurrentUserFromRedis (token);
            int OrgUserDto; //  操作用户表时的返回值
            int OrgTeacherDto;//  操作教师表时的返回值
            //用户状态=1；
            orgTeacherDtoS.setUserstate (1);
            //是否教师=1；
            orgTeacherDtoS.setIsteacher (1);
            // 是否销售人员=0；
            orgTeacherDtoS.setIsteacher (0);
            //1 根据用户id。查询到所在机构id->odgId
            if (user.getUser ().getUserid () != null) {
                Organization orgUserid = orgMapper.selectOne (new QueryWrapper<Organization> ().eq ("orguserid", user.getUser ().getUserid ()).select ("orgid"));
                // 设置机构
                orgTeacherDtoS.setTecorgid (orgUserid.getOrgid ());
            }
            // 加密
            if (orgTeacherDtoS.getUserpwd () != null) {
                orgTeacherDtoS.setUserpwd (DigestUtils.md5DigestAsHex (DigestUtils.md5DigestAsHex (orgTeacherDtoS.getUserpwd ().getBytes ()).getBytes ()));
            }
            orgTeacherDtoS.setCreatetime (new Date ());
            // 操作用户表 用户名 username, 姓名 usertruename,密码 userpwd,专业 usermajor,联系电话 userphone,Email useremail,照片 showpic,用户状态=1；是否教师=1；是否销售人员=0；
            // 用mybatis  返回了用户id 在mapper.xml里面加的配置
            try {
                OrgUserDto = orgTeacherMapper.insertOrgUserDto (orgTeacherDtoS);
                if (OrgUserDto == 0) {
                    throw new Exception ("添加用户信息失败！");
                }
                OrgTeacherDto = orgTeacherMapper.insertOrgTeacherDto (orgTeacherDtoS);
                if (OrgTeacherDto == 0) {
                    throw new Exception ("添加教师表信息失败！");
                }
            } catch (Exception e) {
                e.printStackTrace ();
                // @Transactional和try catch捕获异常会让注解失效
                TransactionAspectSupport.currentTransactionStatus ().setRollbackOnly ();
                return 0;
            }
            //  操作教师表  教师 Title，tecdesc 教师简介 ，tecorgid 教师所属机构=登录用户所属机构 ，技术标签  teclabel, userid 用户id,
            return OrgTeacherDto;
        }
        return 0;
    }

    /**
     * 根据教师所属机构id （tecOrgId）询本机构所有在职老师
     * （修改课表中的：课程教师id和课程教师姓名两个字段）
     *
     * @param tecOrgId
     * @return List<Teacher>
     */
    @Override
    public List<UserTeacherDto> selectListByTecOrgId(Integer tecOrgId) {
        return orgTeacherMapper.selectListByTecOrgId (tecOrgId);
    }
}
